﻿using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.UI.WebControls;
using Blog.Common.Helpers;
using Business;
using Common.Constant;

namespace admincp
{
    public partial class User : System.Web.UI.Page
    {
        private UsersBus _usersBus;
        private Entity.User _userEntity;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["User"] == null || Session["Role"].ToString() != DBSchemas.AdminRoleName)
            {
                Response.Redirect("~/Default.aspx");
            }
            if (Request.QueryString["user"] != null && Request.QueryString["user"] != "" && Request.QueryString["ac"]=="edit")
            {
                try
                {
                    string username = CryptographyHelper.Base64Decode(Request.QueryString["user"]);
                    LoadEditData(username);
                    pnEditor.Visible = true;
                    //pnView.Visible = false;
                }
                catch (Exception exception)
                {
                    Response.Write(exception.Message);
                }
                

            }
            else if (Request.QueryString["user"] != null && Request.QueryString["user"] != "" && Request.QueryString["ac"] == "del")
            {
                try
                {
                    string username = CryptographyHelper.Base64Decode(Request.QueryString["user"]);
                    _usersBus = new UsersBus();
                    if (_usersBus.DeleteUser(username))
                    {
                        Response.Redirect("User.aspx");
                    }
                    else
                    {
                        UIMessage.ShowMessage(UIMessage.CannotDeleteUser, this);
                    }
                }
                catch (Exception exception)
                {
                    //Response.Write(exception.Message);
                    UIMessage.ShowMessage(UIMessage.CannotDeleteUser, this);
                }
                finally
                {
                    Response.Redirect("User.aspx");
                }
            }
            else
            {
                LoadListUser();
                pnView.Visible = true;
                pnEditor.Visible = false;
            }
            LoadEditor();
        }
        private void LoadEditor()
        {
            txtMoreInfo.ToolbarStartupExpanded = false;
            txtMoreInfo.config.toolbar = new object[]
			{
				new object[] { "Source", "-", "Save", "NewPage", "Preview", "-", "Templates" },
                new object[] { "Bold", "Italic", "Underline", "Strike", "-", "Subscript", "Superscript" },
                new object[] { "NumberedList", "BulletedList", "-", "Outdent", "Indent", "Blockquote", "CreateDiv" },
				"/",
				new object[] { "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock" },
				new object[] { "Link", "Unlink", "Anchor" },
				new object[] { "Image", "Flash", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak", "Iframe" },
                new object[] { "BidiLtr", "BidiRtl" },
				"/",
				new object[] { "Styles", "Format", "Font", "FontSize" },
				new object[] { "TextColor", "BGColor" },
				new object[] { "Maximize", "ShowBlocks", "-", "About" }
			};
        }
        protected void ButtonUploadClick(Object sender, EventArgs e)
        {
            UploadPhoto(fuPhoto);
        }
        protected void UploadPhoto(FileUpload fu)
        {
            if (fu.HasFile)
            {
                try
                {
                    if (fu.PostedFile.ContentType == "image/jpeg" || fu.PostedFile.ContentType == "image/gif" || fu.PostedFile.ContentType == "image/png")
                    {
                        if (fu.PostedFile.ContentLength < 4096000)
                        {
                            const int thumbWidth = 150;
                            const int thumbHeight = 110;

                            System.Drawing.Image oImg = System.Drawing.Image.FromStream(fu.PostedFile.InputStream);
                            System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                            System.Drawing.Image phoi = new Bitmap(Server.MapPath("~/resource/images/b.png"));

                            Graphics oGraphic = Graphics.FromImage(oThumbNail);
                            oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                            oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                            oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                            var oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                            oGraphic.DrawImage(oImg, oRectangle);
                            oGraphic.DrawImage(phoi, 120, 80);

                            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                            oThumbNail.Save(Server.MapPath("~/resource/upload/") + filename, ImageFormat.Jpeg);
                            oImg.Dispose();

                            TextBoxPhoto.Text = "resource/upload/avatar/" + filename;
                            LabelMessage.Text = UIMessage.UploadSuccess;
                            LabelMessage.ForeColor = Color.Blue;
                        }
                        else
                            LabelMessage.Text = UIMessage.MaxUploadSize;
                    }
                    else
                        LabelMessage.Text = UIMessage.OnlyImageFileAccepted;
                }
                catch (Exception ex)
                {
                    LabelMessage.Text = UIMessage.UploadError + ex.Message;
                }
            }
        }
        protected bool CheckUserIsExists(string userName)
        {
            _usersBus = new UsersBus();
            return _usersBus.CheckUserIsExists(userName);
        }
        protected void ButtonSubmitClick(object sender, EventArgs e)
        {
            try
            {
                if (ButtonSubmit.Text == "Lưu sửa đổi")
                {
                    _usersBus = new UsersBus();
                    _userEntity = new Entity.User()
                                      {
                                          UserName = TextBoxName.Text.Trim(),
                                          Password = TextBoxPassword.Text != "" ? HiddenFieldPassword.Value : CryptographyHelper.EncryptPassword(TextBoxPassword.Text),
                                          IsAdmin = DropDownListUserType.SelectedIndex == 0 ? false : true,
                                          Email = TextBoxEmail.Text,
                                          FullName = TextBoxFullName.Text,
                                          DateOfBirth = DateTime.Parse(TextBoxDateOfBirth.Text),
                                          AvatarPath = TextBoxPhoto.Text,
                                          JoinDate = DateTime.Now,
                                          MoreInfo = txtMoreInfo.Text,
                                          IsLock = false
                                      };
                    if (_usersBus.UpdateUser(_userEntity))
                    {
                        UIMessage.ShowMessage("Cập nhật thành công", this);
                        //Response.Redirect("~/Default.aspx");
                    }
                    else
                    {
                        UIMessage.ShowMessage("Cập nhật thất bại", this);
                    }
                }
                else
                {

                    if (CheckUserIsExists(TextBoxName.Text.Trim()))
                    {
                        UIMessage.ShowMessage(UIMessage.UserIsExists, this);
                    }
                    else
                    {
                        _usersBus = new UsersBus();
                        _userEntity = new Entity.User()
                        {
                            UserName = TextBoxName.Text.Trim(),
                            Password = CryptographyHelper.EncryptPassword(TextBoxPassword.Text),
                            IsAdmin = false,
                            Email = TextBoxEmail.Text,
                            FullName = TextBoxFullName.Text,
                            DateOfBirth = DateTime.Parse(TextBoxDateOfBirth.Text),
                            AvatarPath = TextBoxPhoto.Text,
                            JoinDate = DateTime.Now,
                            MoreInfo = txtMoreInfo.Text,
                            IsLock = false
                        };
                        if (_usersBus.AddUser(_userEntity))
                        {
                            UIMessage.ShowMessage("Thêm người dùng thành công", this);
                            //Response.Redirect("~/Default.aspx");
                        }
                        else
                        {
                            UIMessage.ShowMessage("Thêm người dùng thất bại", this);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Response.Write(exception.Message);
            }
        }
        protected void LoadEditData(string userName)
        {
            _usersBus = new UsersBus();
            DataSet userInfo = _usersBus.GetUserByUserName(userName);
            if (userInfo.Tables[0].Rows.Count > 0)
            {
                TextBoxName.Text = userInfo.Tables[0].Rows[0]["UserName"].ToString();
                TextBoxName.Enabled = false;
                HiddenFieldPassword.Value = userInfo.Tables[0].Rows[0]["Password"].ToString();
                TextBoxFullName.Text = userInfo.Tables[0].Rows[0]["FullName"].ToString();
                TextBoxEmail.Text = userInfo.Tables[0].Rows[0]["Email"].ToString();
                TextBoxPhoto.Text = userInfo.Tables[0].Rows[0]["AvatarPath"].ToString();
                TextBoxDateOfBirth.Text = userInfo.Tables[0].Rows[0]["DateOfBirth"].ToString();
                txtMoreInfo.Text = userInfo.Tables[0].Rows[0]["MoreInfo"].ToString();
                DropDownListUserType.SelectedIndex = userInfo.Tables[0].Rows[0]["IsAdmin"].ToString() == "True" ? 1 : 0;
                ButtonSubmit.Text = "Lưu sửa đổi";
            }
        }
        protected void LoadListUser()
        {
            try
            {
                _usersBus = new UsersBus();
                DataSet allUser = _usersBus.SelectAllUser();
                RepeaterListUser.DataSource = allUser;
                RepeaterListUser.DataBind();
            }
            catch(Exception ex){
                Response.Write(ex.Message);
            }
        }
    }
}
